package com.example.bootes.controller;

import com.example.bootes.entity.IndexEntity;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * @author daxue0929
 * @date 2022/8/23
 */

@Slf4j
@RestController
@RequestMapping("/index")
public class IndexController {

    final RestHighLevelClient client;

    @Autowired
    public IndexController(RestHighLevelClient client) {
        this.client = client;
    }

    @PostMapping("/create")
    public CreateIndexResponse create(@RequestBody IndexEntity indexEntity) throws IOException {

        IndicesClient indices = client.indices();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexEntity.getName());
        CreateIndexResponse indexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
        boolean acknowledged = indexResponse.isAcknowledged();
        log.info("当前创建索引: {}, 是否创建成功: {}", indexEntity.getName(), acknowledged);
        return indexResponse;
    }

    @DeleteMapping("/{index}")
    public ActionResponse delete(@PathVariable String index) throws IOException {
        IndicesClient indices = client.indices();
        DeleteIndexRequest deleteRequest = new DeleteIndexRequest(index);

        AcknowledgedResponse response = null;
        try {
            response = indices.delete(deleteRequest, RequestOptions.DEFAULT);
            log.info("当前删除索引: {}, 是否删除成功: {}", index, response.isAcknowledged());
        } catch (ElasticsearchStatusException e) {
            log.error(e.getMessage());
        }
        return response;
    }
}
